<template>
    <view>
        <view>
            <view class="customer-column" v-if="customColumn && !readyOnly">
                <view>
                    <mySelect :range="columns" multiple size="large" label_name="titleName" value_name="fieldName"
                        v-model="isUseColumn" @change="onCustomColumnChange">选取字段</mySelect>
                </view>
            </view>
            <view class="top-right">
                <slot name="topRight"></slot>
            </view>
        </view>
        <view class="table-container">
            <table class="res-table">
                <tbody>
                    <tr>
                        <slot name="beforeTh"></slot>
                        <th v-for="(column, index) in columns" :key="index" v-show="column.isShow !== 0">
                            {{ column.titleName }}
                            <view v-if="column.isDelColumn && !readyOnly" class="btn "
                                @click="removeOneColumn(index, column)">
                                <text class="cuIcon-roundclose"></text>
                            </view>
                        </th>
                        <slot name="afterTh"></slot>
                        <th v-if="list && list.length && !readyOnly" class="operation"
                            style="min-width:230rpx; width: 230rpx">
                            操作</th>
                    </tr>
                    <tr v-for="(row, index) in list" :key="index">
                        <slot name="beforeTd" :row="row" :rowIndex="index"></slot>
                        <td :align="column.align || 'left'" :style="{ width: column.fieldName === 'index' ? '60rpx' : '' }"
                            v-for="(column, columnIndex) in columns" :key="column.fieldName" v-show="column.isShow !== 0">
                            <!-- <view class="bg-img" v-if="column.fieldName === 'structuralFormula'">
                                <image :src="row[column.fieldName]" mode="aspectFill"
                                    @tap="viewImage(row[column.fieldName])"></image>
                            </view>
                            <myInput v-else-if="column.formType === 0" size="large" clearable
                                v-model="row[column.fieldName]" :type="column.input_type || 'text'" :unit="column.unit">
                            </myInput>
                            <myInput v-else-if="column.formType === 'textarea'" size="large" autoHeight
                                v-model="row[column.fieldName]" type="textarea"></myInput>
                            <mySelect v-else-if="column.formType === 1" filterable clearable customer :range="materialList"
                                size="large" value_name="chemicalName" label_name="chemicalName"
                                v-model="row[column.fieldName]" @panelShow="getMaterial(column, columnIndex)"
                                @change="(v, o) => physicoChemicalSetRow(o, row)">
                                <template v-slot:option="{ data }">
                                    <view class="select_option">
                                        <view class="title">
                                            <text>{{ data.chemicalName }}</text>
                                            <text class="sub_title"> （{{ data.chemicalCode }}）</text>
                                        </view>
                                        <view class="sub_title">{{ data.chemicalStd }}</view>
                                    </view>
                                </template>
                            </mySelect>
                            <date-time-picker v-else-if="column.formType === 2" format="YYYY-MM-DD HH:mm:ss" type="datetime"
                                :border="false" :clear-icon="false" value-format="YYYY-MM-DD HH:mm:ss"
                                v-model="row[column.fieldName]" placeholder="请选择">
                            </date-time-picker>

                            <text v-else-if="!canWrite || readyOnly" class="text">{{
                                row[column.fieldName] || (column.fieldName === 'index' ? index + 1 : "") }}</text> -->
                            <text class="text">{{ row[column.fieldName] || (column.fieldName === 'index' ? index + 1
                                : "")
                            }}</text>
                        </td>
                        <slot name="afterTd" :row="row" :rowIndex="index"></slot>
                        <td v-if="!readyOnly" align="center" class="operation">
                            <text v-if="canSorted && index > 0" class="btn color-primary" @click="moveUp(index)">上移</text>
                            <text v-if="canSorted && index < list.length - 1" class="btn color-primary"
                                @click="moveLower(index)">下移</text>
                            <text class="btn color-danger" @click="removeOneRow(index, row)">移除</text>
                        </td>
                    </tr>
                    <slot name="row"></slot>
                </tbody>
            </table>
        </view>
    </view>
</template>

<script lang="ts" setup>
import myInput from "@/components/myInput";
import mySelect from "@/components/mySelect";
import dateTimePicker from "@/components/dateTimePicker";
import ThTable from './th-table'
import {
    baseRequest
} from "@/utils/api/request";
export default {
    name: "thStep",
    components: {
        myInput,
        mySelect,
        dateTimePicker,
    },
    data() {
        return {
            columns: [], //所有列
            list: [], //行数据
            isUseColumn: [], //当前显示使用的列
            materialList: [] //物料列表
        };
    },
    props: {
        mode: {
            //模式： form和table
            type: String,
            default: "form",
            validator(value) {
                return ["form", "table"].includes(value);
            },
        },
        name: {
            //步骤名成，在添加按钮处显示名称使用
            type: String,
            default: "",
        },
        canAdd: { //是否可以增加一行
            type: Boolean,
            default: true,
        },
        canWrite: { //是否可以填写
            type: Boolean,
            default: true,
        },
        canSorted: { //是否可以排序
            type: Boolean,
            default: true
        },
        readyOnly: { //是否只读
            type: Boolean,
            default: false
        },
        customColumn: {
            //是否可以自定义控制列的显示
            type: Boolean,
            default: false,
        },
        routeId: {
            type: String,
            default: ""
        },
        stepColumn: {
            //列数据
            type: Array,
            default: () => [],
        },
        stepList: {
            // 行数据
            type: Array,
            default: () => [],
        },
    },
    watch: {
        stepColumn: {
            handler(val) {
                this.columns = val;
                if (this.customColumn) {
                    this.isUseColumn = val
                        .filter((item) => item.isShow === 1)
                        .map((item) => item.fieldName);
                }
                // 判断有物料类型的列且物料有值，则需要获取物料列表数据
                setTimeout(() => {
                    if (!this.readyOnly) {
                        const materialColumnIndex = this.columns.findIndex(column => column.isShow && column
                            .formType === 1)
                        console.log(this.columns)
                        const materialColumn = this.columns[materialColumnIndex]
                        console.log(materialColumn)
                        if (materialColumn) {
                            if (this.list.find(row => row[materialColumn.fieldName])) {
                                this.getMaterial(this.columns[materialColumnIndex])
                            }
                        }
                    }
                }, 200)
            },
            deep: true,
            immediate: true,
        },
        stepList: {
            handler(val) {
                this.list = val;
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        onPanenShow(column) {
            if (!column.options || !column.options.length) {
                if (column.dictName) {
                    column.options = this.$store.getters
                        .getDict(column.dictName)
                        .map((item) => {
                            return {
                                name: item.dictLabel,
                                value: item.dictValue,
                            };
                        });
                } else if (column.apiUrl) {
                    baseRequest({
                        type: "get",
                        url: column.apiUrl,
                        data: {},
                        type: "form",
                        needToken: true,
                    }).then((res) => {
                        if (res.code === 0) {
                            column.options = res.data?.list || res.data || [];
                        } else {
                            uni.showToast({
                                title: res.msg,
                                icon: "none",
                            });
                        }
                    });
                }
            }
        },
        /**
         * 获取路线id
         */
        getRouteId() {
            return this.routeId
        },
        getMaterial(column) {
            debugger
            const routeId = this.getRouteId()
            if (!column.options || !column.options.length) {
                baseRequest({
                    type: "get",
                    url: `/open/base/chemical/info/page`,
                    data: {
                        pageSize: 1000
                    },
                    type: "json",
                    needToken: true,
                }).then((res) => {
                    if (res.code === 0) {
                        column.options = res.data.list || [];
                        this.materialList = res.data.list
                        console.log(this.materialList)
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: "none",
                        });
                    }
                }).catch(err => {
                    console.log(err)
                    uni.showToast({
                        title: err.msg || err.message || '获取化学品失败',
                        icon: "none",
                        duration: 3000,
                    });
                });
            }
        },
        showAddColumn() {
            uni.showModal({
                title: "请输入字段名",
                editable: true,
                success: (res) => {
                    if (res.content) {
                        console.log(res.content)
                        this.addOneColumn(res.content)
                    } else {
                        uni.showToast({
                            title: "请输入字段名",
                            icon: "none"
                        })
                    }
                }
            })
        },
        getLastColumnFieldNumber() {
            //TODO 优先使用中间缺少的字段
            const last = this.columns[this.columns.length - 1]
            const lastField = last?.fieldName || ""
            const lastIndex = Number(lastField.replace("cdefine", ""))
            return lastIndex || 0
        },
        // 添加一列
        addOneColumn(titleName, index = this.columns.length - 1) {
            const newColumn = {
                titleName,
                fieldName: `cdefine${this.getLastColumnFieldNumber() + 1}`,
                fieldType: "varchar",
                formType: 0,
                isShow: 1,
                isRequired: 1
            }
            this.columns.splice(index + 1, 0, newColumn);
        },
        // 删除一列
        removeOneColumn(index, column) {
            // if (this.columns.length === 1) {
            // 	uni.showToast({
            // 		title: "请至少保留一个",
            // 		icon: "none",
            // 	});
            // 	return;
            // }
            // 判断如果是已经保存的则将isShow设置为false，否则删除
            if (column.id) {
                column.isShow = 0
                // 清除所有数据中此列的数据
                // this.list.forEach(item => {
                // 	item[column.fieldName] = ""
                // })
            } else {
                this.columns.splice(index, 1);
                // 删除所有数据中此列的数据
                this.list.forEach(item => {
                    delete item[column.fieldName]
                })
            }
        },
        // 添加一行
        addOneRow(index) {
            const newStep = {};
            const firstStep = this.list[0];
            if (firstStep) {
                for (let key in firstStep) {
                    if (typeof firstStep[key] === "string") {
                        newStep[key] = "";
                    }
                    if (Array.isArray(firstStep[key])) {
                        newStep[key] = [];
                    }
                }
            }
            this.list.splice(index + 1, 0, newStep);
        },
        // 删除一行
        removeOneRow(index, row) {
            // if (this.list.length === 1) {
            // 	uni.showToast({
            // 		title: "请至少保留一个",
            // 		icon: "none",
            // 	});
            // 	return;
            // }
            this.list.splice(index, 1);
            this.$emit('delRow', index, row)
        },
        // 向下移动
        moveLower(index) {
            if (index === this.list.length - 1) {
                return;
            }
            let temp = this.list[index + 1];
            this.list[index + 1] = this.list[index];
            this.list[index] = temp;
            this.list = [...this.list];
        },
        // 向上移动
        moveUp(index) {
            if (index === 0) {
                return;
            }
            let temp = this.list[index - 1];
            this.list[index - 1] = this.list[index];
            this.list[index] = temp;
            this.list = [...this.list];
        },
        // 列项目改变时触发
        onCustomColumnChange(e) {
            this.columns.forEach((item) => {
                if (e.includes(item.fieldName)) {
                    item.isShow = 1;
                } else {
                    item.isShow = 0;
                }
            });
        },
        // 查看图片
        viewImage(url) {
            uni.previewImage({
                urls: [url],
                current: url,
            });
        },

        physicoChemicalSetRow(option, row) {
            const rows = JSON.parse(JSON.stringify(row));
            Object.keys(rows).map(item => {
                this.$set(row, item, option[0][item])
            })
            console.log(row)
        }
    },
};
</script>

<style scoped lang="scss">
@import "../../../experiment-project/project-approval/table.scss";

.row-list {
    display: flex;
    flex-wrap: wrap;

    &:after {
        content: "";
        min-width: 540rpx;
        margin: 0 24rpx;
        flex: 1;
        height: 0;
    }

    .text {
        line-height: 42rpx;
    }
}

.customer-column {
    display: flex;
    align-items: center;
    margin-bottom: 6rpx;

    .add-column-btn {
        padding: 6rpx;
        font-size: 0.8125rem;
    }
}

.form-item {
    .btn {
        padding: 6rpx;
        margin-left: 12rpx;
    }
}

.add_person_btn {
    margin-top: 24rpx;
    padding: 12rpx;
    border-radius: 6rpx;
    border: 1rpx dashed $color-highlight;
    text-align: center;
    color: $color-highlight;
}

table {
    // border-collapse: collapse;
    // width: 100%;
    // font-size: 0.875rem;
    // font-weight: initial;

    // tr:nth-child(2n + 3) {
    // 	background-color: #f8fbff;
    // }

    th {
        // box-sizing: border-box;
        // min-width: 160rpx;
        // padding: 10rpx;
        // height: 88rpx;
        // position: relative;
        // font-size: 0.875rem;
        // // font-weight: initial;
        // white-space: pre-line;
        // word-break: break-all;
        // // border: 1rpx solid #666;
        // border: 1rpx solid #dedede;
        // background-color: #f7f7f7;
        // color: #777;

        &[align="center"] {
            text-align: center;
        }

        &[align="left"] {
            text-align: left;
        }

        &[align="right"] {
            text-align: right;
        }

        .btn {
            padding: 6rpx;
            position: absolute;
            top: 0;
            right: 0;
        }
    }

    td {
        // box-sizing: border-box;
        // padding: 10rpx;
        // height: 88rpx;
        // min-width: 80rpx;
        // position: relative;
        // font-size: 0.875rem;
        // white-space: pre-line;
        // word-break: break-all;
        // // border: 1rpx solid #666;
        // border: 1rpx solid #dedede;
        // background-color: #fff;

        &[align="center"] {
            text-align: center;
        }

        &[align="left"] {
            text-align: left;
        }

        &[align="right"] {
            text-align: right;
        }

        textarea {
            width: auto;
            font-size: 0.875rem;
        }

        input {
            font-size: 0.875rem;
        }

        .inline-content {
            input {
                height: 28rpx;
                width: 60rpx;
                line-height: 28rpx;
                text-align: center;
                display: inline-block;
                position: relative;
                top: 12rpx;
                font-size: 0.875rem;
            }
        }

        /deep/.uniui-calendar {
            display: none;
        }

        /deep/.uni-date__x-input {
            height: 40rpx;
            line-height: 40rpx;
            padding: 0;
            font-size: 0.875rem !important;
            color: #8a929f;
        }

        .more-text {
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            display: -webkit-box;
        }

        .link {
            color: $color-primary;
        }

        .bg-img {
            width: 90rpx;
            height: 90rpx;

            uni-image {
                width: 100%;
                height: 100%;
            }
        }
    }
}

.table-container {
    width: 100%;
    // max-height: 60vh;
    overflow: auto;

    // pointer-events: all;
    &::-webkit-scrollbar {
        display: initial;
        width: 8rpx;
        height: 10rpx;
        -webkit-border-radius: 8rpx;
        -moz-border-radius: 8rpx;
        border-radius: 8rpx;
    }

    &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.3);
        background-clip: padding-box;
        -webkit-border-radius: 8rpx;
        -moz-border-radius: 8rpx;
        border-radius: 8rpx;
        min-height: 10rpx;
    }

    &::-webkit-scrollbar-thumb:hover {
        background-color: rgba(0, 0, 0, 0.5);
        -webkit-border-radius: 8rpx;
        -moz-border-radius: 8rpx;
        border-radius: 8rpx;
    }
}


.select_option {
    text-align: left;
    margin-top: 2rpx;

    .title {
        margin-bottom: 4rpx;
        font-size: 0.875rem;
    }

    .sub_title {
        font-size: 26rpx;
        color: #666;
    }
}

.operation {

    // position: sticky;
    // right: 0;
    // box-shadow: 0 28rpx 0 28rpx #e0e0e0;
    // z-index: 2;
    .btn {
        padding: 6rpx;
        font-size: 0.8125rem;
    }
}
</style>
